package com.igd.interceptors;

import java.util.Iterator;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.igd.action.BaseAction;
import com.igd.common.constant.RequestConstant;
import com.igd.pojo.vo.PageList;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.opensymphony.xwork2.interceptor.PreResultListener;

 /**
 * @version  1.0
 *
 * @author   QIAOYU
 *
 * @date     2013-6-27
 *
 * @description	 请求响应拦截器,此拦截器将Action中的page分页对象放入Request请求中,将分页查询的条件放入Request在页面返显
 */

public class ResponseInterceptor extends AbstractInterceptor {

	private static final long serialVersionUID = 8283444026326475887L;

	public String intercept(ActionInvocation invocation) throws Exception {
		
		final BaseAction base = (BaseAction) invocation.getAction();
		
		invocation.addPreResultListener(new PreResultListener(){

			public void beforeResult(ActionInvocation invocation,String resultCode) {
				
				PageList pageList = base.getPage();
				
				if(null != pageList){
					
					ActionContext ctx = invocation.getInvocationContext();
					
					if(!pageList.getParam().isEmpty()){
						
						Map<String,String> params = pageList.getParam();
						
						Iterator<String> it = params.keySet().iterator();
						
						while(it.hasNext()){
							
							String paramKey = it.next();
							
							if(StringUtils.isNotEmpty(paramKey)){
								
								String paramVal = params.get(paramKey);
								
								ctx.put(paramKey,paramVal);

							}
						}
					}
					
					ctx.put(RequestConstant.PAGE_LIST_KEY, pageList);
				}
			}
		});
		
		return invocation.invoke();
	}
}
